package com.uduemc.biso.node.web.api.controller.noauthentication.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.uduemc.biso.node.core.common.dto.TemplateTempCache;
import com.uduemc.biso.node.web.api.component.TemplateAsync;
import com.uduemc.biso.node.web.api.service.TemplateService;

import cn.hutool.core.util.URLUtil;

@RequestMapping("/api/service/master")
@Controller
public class ASTemplateController {

	@Autowired
	private TemplateService templateServiceImpl;

	@Autowired
	private TemplateAsync templateAsync;

	/**
	 * 同步的方式通过 hostId、siteId、key 生成 template.zip 文件
	 * 
	 * @param hostId
	 * @param siteId
	 * @param key
	 * @throws Exception
	 */
	@PostMapping("/template/make")
	@ResponseBody
	public String make(@RequestParam("hostId") long hostId, @RequestParam("siteId") long siteId,
			@RequestParam("key") String key) throws Exception {
		int makeTemplateZip = templateServiceImpl.makeTemplateZip(hostId, siteId, key);
		if (makeTemplateZip == 0) {
			return key;
		}
		// 生成下载链接，返回下载链接
		return String.valueOf(makeTemplateZip);
	}

	/**
	 * 异步的方式通过 hostId、siteId、key 生成 template.zip 文件
	 * 
	 * @param hostId
	 * @param siteId
	 * @param key
	 * @throws Exception
	 */
	@PostMapping("/template/async-make")
	@ResponseBody
	public String asyncMake(@RequestParam("hostId") long hostId, @RequestParam("siteId") long siteId,
			@RequestParam("key") String key) throws Exception {
		templateAsync.makeTemplate(hostId, siteId, key);
		return key;
	}

	/**
	 * 通过 key 验证是否已经完成生成模板文件，如果完成返回下载地址，如果未完成返回 -1
	 * 
	 * @param key
	 * @return
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	@GetMapping("/template/download/{key}")
	public void complete(@PathVariable("key") String key, HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		TemplateTempCache templateTempCache = templateServiceImpl.getTemplateTempCache(key);
		if (templateTempCache == null) {
			// 不存在缓存内容
			response.getWriter().write("-1");
			return;
		}
		String zipPath = templateTempCache.getZipPath();
		File file = new File(zipPath);
		if (!file.isFile()) {
			// 不存在的文件
			response.getWriter().write("-2");
			return;
		}
		try (InputStream inputStream = new FileInputStream(file);
				OutputStream outputStream = response.getOutputStream()) {
			String filename = zipPath.substring(zipPath.lastIndexOf("/") + 1);
			response.setContentType("application/x-download");
			response.setHeader("Accept-Ranges", "bytes");
			response.setHeader("Accept-Length", String.valueOf(templateTempCache.getZipSize()));
			response.setHeader("Content-Length", String.valueOf(templateTempCache.getZipSize()));
			response.setHeader("Content-Disposition", "attachment;filename=" + URLUtil.encode(filename));

			IOUtils.copy(inputStream, outputStream);
			outputStream.flush();
		}
	}
}
